package com.example.message_queue.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-03-23
 * Time:14:22
 * Text：交换机
 */

public class Exchange {
    //name作为交换机的身份标识
    @Getter
    private String name;
    //交换机类型，DIRECT、FANOUT、TOPIC
    @Getter
    private ExchangeType type = ExchangeType.DIRECT;
    //durable表示交换机是否需要持久化存储，
    private boolean durable = false;
    //交换机无人使用则自动被删除
    @Getter
    private boolean autoDelete = false;

    public void setName(String name) {
        this.name = name;
    }

    public void setType(ExchangeType type) {
        this.type = type;
    }

    public boolean getDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    //表示创建交换机时指定的额外参数，未实现
    private Map<String, Object> arguments = new HashMap<>();

    public String getArguments() {
        //将当前的arguments参数，从map转化为String
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }
    //从数据库中读取时，构造Exchange对象
    public void setArguments(String argumentsJson){
        //把参数中的argumentsJson按照为json格式解析为map对象
        ObjectMapper objectMapper=new ObjectMapper();

        try {
            this.arguments=objectMapper.readValue(argumentsJson, new TypeReference<HashMap<String,Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    //
    public void setArguments(Map<String,Object> arguments) {
        this.arguments = arguments;
    }


    //测试用例的键值对
    public Object getArguments(String Key) {
        return arguments.get(Key);
    }
    public void setArguments(String Key,Object value){
        arguments.put(Key,value);
    }
}
